


from rest_framework import serializers
from rest_framework.serializers import SerializerMethodField
from .models import Book, Author, Publisher, BookReview
from django.contrib.auth import get_user_model

User = get_user_model()

class AuthorSerializer(serializers.ModelSerializer):
    book_count = serializers.IntegerField(read_only=True)
    
    class Meta:
        model = Author
        fields = ['id', 'name', 'email', 'birth_date', 'book_count']
        read_only_fields = ['book_count']

class PublisherSerializer(serializers.ModelSerializer):
    class Meta:
        model = Publisher
        fields = ['id', 'name', 'code']

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['id', 'username', 'email']

class BookReviewSerializer(serializers.ModelSerializer):
    user = UserSerializer(read_only=True)
    
    class Meta:
        model = BookReview
        fields = ['id', 'user', 'rating', 'review', 'created_at']
        read_only_fields = ['user', 'created_at']

class BookSerializer(serializers.ModelSerializer):
    author = AuthorSerializer()
    publisher = PublisherSerializer(required=False)
    reviews = BookReviewSerializer(many=True, read_only=True)
    status_display = serializers.CharField(source='get_status_display', read_only=True)
    
    class Meta:
        model = Book
        fields = [
            'id', 'title', 'slug', 'author', 'publisher', 
            'publish_date', 'status', 'status_display', 'isbn', 
            'price', 'pages', 'reviews'
        ]
        read_only_fields = ['slug']
    
    def create(self, validated_data):
        author_data = validated_data.pop('author')
        author = Author.objects.get_or_create(**author_data)[0]
        
        publisher_data = validated_data.pop('publisher', None)
        publisher = None
        if publisher_data:
            publisher = Publisher.objects.get_or_create(**publisher_data)[0]
        
        book = Book.objects.create(author=author, publisher=publisher, **validated_data)
        return book
    
    def update(self, instance, validated_data):
        author_data = validated_data.pop('author', None)
        if author_data:
            author = Author.objects.get_or_create(**author_data)[0]
            instance.author = author
        
        publisher_data = validated_data.pop('publisher', None)
        if publisher_data:
            publisher = Publisher.objects.get_or_create(**publisher_data)[0]
            instance.publisher = publisher
        
        for attr, value in validated_data.items():
            setattr(instance, attr, value)
        
        instance.save()
        return instance

class BookLoanSerializer(serializers.ModelSerializer):
    book = serializers.PrimaryKeyRelatedField(queryset=Book.objects.all())
    user = serializers.PrimaryKeyRelatedField(queryset=User.objects.all())
    
    class Meta:
        model = BookLoan
        fields = ['id', 'book', 'user', 'loan_date', 'due_date', 'return_date']
        read_only_fields = ['loan_date']
    
    def validate(self, data):
        book = data.get('book')
        user = data.get('user')
        
        if book and user:
            active_loan = BookLoan.objects.filter(
                book=book, 
                user=user, 
                return_date__isnull=True
            ).exists()
            
            if active_loan:
                raise serializers.ValidationError("This user already has an active loan for this book.")
        
        return data